package cn.wh.util;

import cn.wh.config.JWTProperties;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Map;

/**
 * @Author wanghao
 * @Date 2022/4/29 17:51
 * @Description: TODO
 */
public class JWTUtils {

    // 签名密钥
    private static final String SECRET = "!DAR$";

    @Bean
    public JWTProperties getJwtProperties() {
        return new JWTProperties();
    }

    /**
     * 生成token
     *
     * @param payload token携带的信息
     * @return token字符串
     */
    public static String getToken(Map<String, String> payload) {
        // 指定token过期时间为7天
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 7);

        JWTCreator.Builder builder = JWT.create();
        // 构建payload
        payload.forEach((k, v) -> builder.withClaim(k, v));
        // 指定过期时间和签名算法
        String token = builder.withExpiresAt(calendar.getTime()).sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    /**
     * 解析token
     *
     * @param token
     * @return
     */
    public static DecodedJWT decode(String token) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT decodedJWT = null;
        try {
            decodedJWT = jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            e.printStackTrace();
        }
        return decodedJWT;
    }

}
